---
import { type CollectionEntry, getCollection } from 'astro:content';
import BlogPost from '../../layouts/BlogPost.astro';
import { render } from 'astro:content';
import { processFrontmatter } from '../../integrations/process-frontmatter';

export async function getStaticPaths() {
	const posts = await getCollection('posts');
	const processedPosts = await Promise.all(
		posts.map(async (post) => {
			const processedPost = await processFrontmatter(post);
			return processedPost;
		})
	);

	// 按日期排序文章，最新的文章在前
	const sortedPosts = processedPosts.sort((a, b) => {
		const dateA = a.data.date ? new Date(a.data.date).getTime() : 0;
		const dateB = b.data.date ? new Date(b.data.date).getTime() : 0;
		return dateB - dateA;
	});
	
	return sortedPosts.map((post, index) => {
		// 使用官方 API 方式：直接在 props 中提供 prev 和 next
		const prevPost = index < sortedPosts.length - 1 ? sortedPosts[index + 1] : null;
		const nextPost = index > 0 ? sortedPosts[index - 1] : null;
		
		return {
			params: { slug: post.data.abbrlink },
			props: { 
				post,
				prev: prevPost ? {
					title: prevPost.data.title,
					url: `/posts/${prevPost.data.abbrlink}/`
				} : null,
				next: nextPost ? {
					title: nextPost.data.title,
					url: `/posts/${nextPost.data.abbrlink}/`
				} : null
			},
		};
	});
}

type Props = {
	post: CollectionEntry<'posts'>;
	prev: { title: string; url: string } | null;
	next: { title: string; url: string } | null;
};

const { post, prev, next } = Astro.props;
const { Content, headings } = await render(post);
---

<BlogPost {...post.data} headings={headings} description={post.body} prev={prev} next={next}>
	<Content />
</BlogPost>
